const { ccclass, property } = cc._decorator;

@ccclass
export default class BScrollView extends cc.Component {

    @property(cc.Node)
    item: cc.Node = null;

    @property(cc.Integer)
    space: number = 0;

    content: cc.Node = null;

    private ccScrollView: cc.ScrollView = null;
    private itemWidth: number;
    private itemHeight: number;

    onLoad() {
        this.tryInit();
        this.item.active = false;
        this.itemWidth = this.item.width;
        this.itemHeight = this.item.height;
    }

    updateSize(item: cc.Node, total: number, index: number) {
        this.tryInit();
        if (this.ccScrollView.horizontal) {
            item.x = this.space + item.width * 0.5 + index * (item.width + this.space);
            if (index == total - 1) {
                this.content.width = this.space + (this.item.width + this.space) * total;
            }
        } else {
            item.x = this.space - item.height * 0.5 - index * (item.width + this.space);
            if (index == total - 1) {
                this.content.height = this.space + (this.item.height + this.space) * total;
            }
        }
    }

    /** 默认停留在第几个索引
     * @param useAnimation 是否使用动画移动过去，默认false
     */
    stopAt(index: number, useAnimation: boolean = false) {
        this.scheduleOnce(() => {
            let viewWidth = this.content.parent.width;
            let viewHeight = this.content.parent.height;
            if (this.ccScrollView.horizontal) {
                let stopX = -viewWidth * 0.5 - index * (this.itemWidth + this.space);
                let minX = -this.content.width + viewWidth * 0.5;
                if (stopX < minX) {
                    stopX = minX;
                }
                if (useAnimation) {
                    cc.tween(this.content).to(0.5, { x: stopX }, { easing: 'sineOut' }).start();
                } else {
                    this.content.x = stopX;
                }
            } else {
                let stopY = viewHeight * 0.5 + index * (this.itemHeight + this.space);
                let maxY = this.content.height - viewHeight * 0.5;
                if (stopY > maxY) {
                    stopY = maxY;
                }
                if (useAnimation) {
                    cc.tween(this.content).to(0.5, { y: stopY }, { easing: 'sineOut' }).start();
                } else {
                    this.content.y = stopY;
                }
            }
        }, 0.1);
    }

    private tryInit() {
        if (!this.ccScrollView) {
            this.ccScrollView = this.getComponent(cc.ScrollView);
        }
        if (!this.content) {
            this.content = this.item.parent;
        }
    }

}
